# -*- coding: utf-8 -*-
""" Auteur: Jordan Guerin """
from Tkinter import *
import datetime
import Calendar
import time
import Sheet

""" Cette classe sert à gérer l'interface graphique reliée au calendrier et aux sprints.
    Responsabilités:
        refreshEventView()
        deleteEvent()
        viewEvent()
        newEvent()
        refresh()
    Collaborateurs:
        Les objets Tkinter associés
        Le client
        Un objet Calendar pour contenir les objets CalendarEvent
"""
class CalendarInterface(object):
    def __init__(self,client):
        self.master = Toplevel()
        self.frame = Frame(self.master)
        self.master.title("Calendrier")
        self.frame.pack()
        self.client = client
        self.calendar = Calendar.Calendar(client.server.getObjectsOfClass(Calendar.CalendarEvent))
        self.sheetsList = client.server.getObjectsOfClass(Sheet.Sheet)
        Label(self.frame, text="Calendrier").grid(row=0,column=2)
        Label(self.frame, text="Début").grid(row=1,column=0)
        Label(self.frame, text="Fin").grid(row=1,column=1)
        Label(self.frame, text="Nom").grid(row=1,column=2)
        Label(self.frame, text="Status").grid(row=1,column=3)
        self.listBox = Listbox(self.frame,height=2)
        
        self.refreshEventView()
    
    def refreshEventView(self):
        
        increment = 2
        
        for i in self.calendar.eventsList:
            
            dateStart = datetime.datetime.fromtimestamp(i.dateStart)
            dateEnd = datetime.datetime.fromtimestamp(i.dateEnd)
            
            tmp_str = str(dateStart.day)
            tmp_str = tmp_str + " " + Calendar.monthsList[dateStart.month-1]
            
            Label(self.frame, text=tmp_str,bg="white").grid(row=increment,column=0)
            
            tmp_str = str(dateEnd.day) + " " + Calendar.monthsList[dateEnd.month-1]
            
            Label(self.frame, text=tmp_str,bg="white").grid(row=increment,column=1)
            
            Label(self.frame, text=i.name,bg="white").grid(row=increment,column=2)
            
            Label(self.frame, text=i.status,bg="white").grid(row=increment,column=3)
            
            
            self.listBox.insert(END,i.name)
            increment = increment + 1 
            
        
        self.listBox.grid(row=increment,column=2)
        Button(self.frame, text="Voir/Modifier", command=self.viewEvent).grid(row=increment,column=3)
        Button(self.frame, text="Nouveau...", command=self.newEvent).grid(row=increment,column=4)
        Button(self.frame, text="Supprimer", command=self.deleteEvent).grid(row=increment,column=5)
    
    def deleteEvent(self):
        name = self.listBox.get(ACTIVE)
        index = Calendar.getEventIndex(name, self.calendar.eventsList)
        self.client.server.deleteObject(self.calendar.eventsList.pop(index))
        self.master.destroy()
        self.refresh()
    
    def viewEvent(self):
        name = self.listBox.get(ACTIVE)
        index = Calendar.getEventIndex(name, self.calendar.eventsList)
        self.eventInterface = CalendarEventInterface(self,self.calendar.eventsList[index])
        
    def newEvent(self):
        self.eventInterface = CalendarEventInterface(self)
        
    def refresh(self):
        self = CalendarInterface(self.client)

""" Cette classe sert à gérer les objets CalendarEvent individuels.
    Responsabilités:
        addSheet()
        removeSheet()
        eventQuit()
        eventSave()
    Colaborateurs:
        L'objet CalendarEvent associé
        L'objet CalendarInterface parent
        Les objets Tkinter associés
"""
class CalendarEventInterface(object):
    def __init__(self,parent,calendarEvent = None):
        self.parent = parent
        self.master = Toplevel()
        self.master.title("Calendrier : Événement")
        self.frame = Frame(self.master)
        self.frame.pack()
        self.event = calendarEvent
        self.name = StringVar()
        Entry(self.frame,width=60,textvariable=self.name).grid(row=1,column=1,columnspan=4)
        #Ancien champ description
        #self.description = Text(self.frame,width=60,height=18)      
        self.listMonthStart = Listbox(self.frame,height=1,selectmode=SINGLE)
        self.listMonthStart.grid(row=4,column=1,columnspan=4)
        self.listMonthEnd = Listbox(self.frame,height=1,selectmode=SINGLE)
        self.listMonthEnd.grid(row=7,column=1,columnspan=4)
        
        Label(self.frame, text="CRC relié(s) :").grid(row=2,column=0)
        self.listSheets = Listbox(self.frame, width=20,height=5,selectmode=SINGLE)
        
        Label(self.frame, text="CRC disponibles(s) :").grid(row=3,column=0)
        self.listAvailableSheets = Listbox(self.frame,  width=20,height=5,selectmode=SINGLE)
        
        
        
        Label(self.frame, text="Créer un évênement").grid(row=0,column=0)
        Label(self.frame, text="Nom : ").grid(row=1,column=0)
        
        Label(self.frame, text="Mois : (Début)").grid(row=4,column=0)
        Label(self.frame, text="Jour : (Début)").grid(row=5,column=0)
        Label(self.frame, text="Année : (Début)").grid(row=6,column=0)
        self.dayStart = StringVar()
        self.yearStart = StringVar()
        Entry(self.frame,textvariable=self.dayStart).grid(row=5,column=1,columnspan=4)
        Entry(self.frame,textvariable=self.yearStart).grid(row=6,column=1,columnspan=4)
        
        Label(self.frame, text="Mois : (Fin)").grid(row=7,column=0)
        Label(self.frame, text="Jour : (Fin)").grid(row=8,column=0)
        Label(self.frame, text="Année : (Fin)").grid(row=9,column=0)
        
        self.yearEnd = StringVar()
        self.dayEnd = StringVar()
        Entry(self.frame,textvariable=self.dayEnd).grid(row=8,column=1,columnspan=4)
        Entry(self.frame,textvariable=self.yearEnd).grid(row=9,column=1,columnspan=4)
        
        Label(self.frame, text="Status :").grid(row=10,column=0)
        self.status = StringVar()
        Entry(self.frame,textvariable=self.status).grid(row=10,column=1,columnspan=4)
        
        for i in parent.sheetsList:
            self.listAvailableSheets.insert(END,i.name)
        
        for i in Calendar.monthsList:
            self.listMonthStart.insert(END,i)
            self.listMonthEnd.insert(END,i)
            
        if calendarEvent == None:
            self.event = Calendar.CalendarEvent("Sans nom",time.time(),time.time(),"0%")      
            calendarEvent = self.event    
        
        if calendarEvent != None:
            title = "Événement :" + self.event.name
            self.master.title(title)
            self.name.set(calendarEvent.name)
            #Ancien champ description
            #Remplacer par les CRC(s)
            #self.description.insert(INSERT,calendarEvent.description)
            self.status.set(calendarEvent.status)
            dateStart = datetime.datetime.fromtimestamp(calendarEvent.dateStart)
            dateEnd = datetime.datetime.fromtimestamp(calendarEvent.dateEnd)
            
            self.listMonthStart.see(dateStart.month-1)
            self.listMonthStart.activate(dateStart.month-1)
            self.listMonthStart.selection_set(dateStart.month-1)
            
            self.listMonthEnd.see(dateEnd.month-1)
            self.listMonthEnd.activate(dateEnd.month-1)
            self.listMonthEnd.selection_set(dateEnd.month-1)
            
            for i in calendarEvent.sheetsLinked:
                self.listSheets.insert(END,i.name)
            
            
            self.dayStart.set(str(dateStart.day))
            self.dayEnd.set(str(dateEnd.day))
            
            self.yearStart.set(str(dateStart.year))
            self.yearEnd.set(str(dateEnd.year))
        #Ancien champ
        #self.description.grid(row=2,column=1)

        self.listSheets.grid(row=2,column=1)
        self.listAvailableSheets.grid(row=3,column=1)
        Button(self.frame, text="Supprimer une fiche", command=self.removeSheet).grid(row=2,column=2)
        Button(self.frame, text="Ajouter une fiche", command=self.addSheet).grid(row=3,column=2)
        Button(self.frame, text="Sauvegarder", command=self.eventSave).grid(row=11,column=1)
        Button(self.frame, text="Fermer", command=self.eventQuit).grid(row=11,column=2)
        
    def addSheet(self):
        index = self.listAvailableSheets.index(ACTIVE)
        self.event.addLinkToSheet(self.parent.sheetsList[index])
        self.listSheets.insert(END,self.parent.sheetsList[index].name)
    
    def removeSheet(self):
        index = self.listSheets.index(ACTIVE)
        self.event.removeLinkToSheet(self.event.sheetsLinked[index])
        self.listSheets.delete(ACTIVE)

    def eventQuit(self):
        self.master.destroy()
        
    def eventSave(self):
        name = self.name.get() 
        index = Calendar.getEventIndex(name, self.parent.calendar.eventsList)
        if index == -1:
            
            dateStart = datetime.datetime(int(self.yearStart.get()),self.listMonthStart.index(ACTIVE)+1,int(self.dayStart.get()))
            dateEnd = datetime.datetime(int(self.yearEnd.get()),self.listMonthEnd.index(ACTIVE)+1,int(self.dayEnd.get()))
            self.event = Calendar.CalendarEvent(name, time.mktime(dateStart.timetuple()), time.mktime(dateEnd.timetuple()), self.status.get())
            
            self.event = self.parent.client.server.setObject(self.event)
            
            self.parent.calendar.addEvent(self.event)
        else:

            dateStart = datetime.datetime(int(self.yearStart.get()),self.listMonthStart.index(ACTIVE)+1,int(self.dayStart.get()))
            dateEnd = datetime.datetime(int(self.yearEnd.get()),self.listMonthEnd.index(ACTIVE)+1,int(self.dayEnd.get())) 
            
            self.event.name = name
            self.event.dateStart = time.mktime(dateStart.timetuple())
            self.event.dateEnd = time.mktime(dateEnd.timetuple())
            self.event.status = self.status.get()
            #Il n'y a plus de champ description
            #event.description = self.description.get(1.0,END)
            self.event = self.parent.client.server.setObject(self.event)
            
            self.parent.calendar.eventsList[index] = self.event
            
        self.frame.forget()
        self.master.destroy()
        #self.parent.frame.forget()
        self.parent.master.destroy()
        self.parent = CalendarInterface(self.parent.client)

client = None
def PlugIn(in_client):
    global client
    client = in_client
    Button(client.frame, text="Calendrier",command=ShowCalendar).pack()
    
    
def ShowCalendar():
    calendarInterface = CalendarInterface(client)
    
